<?php
class ModelSslCustomer extends Model {
    private $_defaultDB = 'customer';

    public function getByPK($pk) {
        $sql = "SELECT * FROM `".DB_PREFIX.$this->_defaultDB."` WHERE `customer_id`='".$pk."'";
        $q = $this->db->query($sql);
        return $q->row;
    }

    public function getCustomerImagesByPK($pk) {
        $cardPic = [];
        $LogoPic = [];
        $Propaganda = [];
        $picList = array();
        $sql = "SELECT U.`upload_id`,CI.`type`,U.`filename` FROM `customer_images` AS CI LEFT JOIN `upload` AS U ON (CI.`code`=U.`code`) WHERE CI.`customer_id`='".$pk."' ORDER BY CI.`customer_images_id` DESC";
        $q = $this->db->query($sql);
        $base_url = $this->config->get('config_url');
        foreach ($q->rows as $row) {
            if (2 == $row['type']) {
                $cardPic[$row['upload_id']] = $base_url.'system/storage/upload/'.$row['filename'];
            }elseif(1 == $row['type']){
                $picList[$row['upload_id']] = $base_url.'system/storage/upload/'.$row['filename'];
            }elseif(3 == $row['type']){
                $LogoPic[$row['upload_id']] = $base_url.'system/storage/upload/'.$row['filename'];
            }elseif(4 == $row['type']){
                $Propaganda[$row['upload_id']] = $base_url.'system/storage/upload/'.$row['filename'];
            }
        }
        return compact('cardPic', 'picList','LogoPic','Propaganda');
    }

    public function loginCheck($name, $pass) {
        $sql = "SELECT * FROM `".DB_PREFIX.$this->_defaultDB."` WHERE (LOWER(`email`)='".$this->db->escape(utf8_strtolower($name))."' OR `telephone`='".$this->db->escape(utf8_strtolower($name))."') AND (`password` = SHA1(CONCAT(`salt`, SHA1(CONCAT(`salt`, SHA1('".$this->db->escape($pass)."'))))) OR `password`= '".$this->db->escape(md5($pass))."') AND `status`='1' AND `approved`='1'";
        $q = $this->db->query($sql);
        $ret = intval($q->row['customer_id']);
        return $ret;
    }

    public function clearBind($wxAppOpenId) {
        $sql = "UPDATE `".DB_PREFIX.$this->_defaultDB."` SET `wx_mp_openid`='' WHERE `wx_mp_openid`='".$wxAppOpenId."'";
        $this->db->query($sql);
    }

    public function userBind($customerId, $wxAppOpenId) {
        $sql = "UPDATE `".DB_PREFIX.$this->_defaultDB."` SET `wx_mp_openid`='".$wxAppOpenId."' WHERE `customer_id`='".$customerId."'";
        $this->db->query($sql);
    }

    public function bindCheck($wxAppOpenId,$shopid) {
        //查customer_in_shop是否已存用户微信信息
        $ret['customerInShopId'] = $this->_getCustomerInShopIdByOpenId($wxAppOpenId,$shopid);
        $sql = "SELECT * FROM `".DB_PREFIX.$this->_defaultDB."` WHERE `wx_mp_openid`='".$wxAppOpenId."'";
        $q = $this->db->query($sql);
        if ($q->num_rows){
            $tmp = $q->row;
            $ret['customerId'] = $tmp['customer_id'];
            $ret['shop_id'] = $tmp['shop_id'];
            //$ret['hasChecked'] = !(bool)$tmp['need_review'];
            if ($userInfo = $this->_getUserIdByTel($tmp['telephone'])) {
                $ret = array_merge($ret, $userInfo);
            }
        }
        return $ret;
    }

    public function updateCustomerInShop($pk, $info) {
        if ($pk) {
            $sql = "UPDATE `".DB_PREFIX."customer_in_shop` SET `nick_name`='".$this->db->escape($info['nickName'])."',`gender`='".$this->db->escape($info['gender'])."',`country`='".$this->db->escape($info['country'])."',`city`='".$this->db->escape($info['city'])."',`province`='".$this->db->escape($info['province'])."',`language`='".$this->db->escape($info['language'])."',`pic`='".$this->db->escape($info['avatarUrl'])."',`data_in_json`='".$this->db->escape(json_encode($info))."' WHERE `customer_in_shop_id`='".$pk."'";
            $this->db->query($sql);
        }
    }

    protected function _getCustomerInShopIdByOpenId($openId,$shopid) {
        $sql = "SELECT `customer_in_shop_id` FROM `".DB_PREFIX."customer_in_shop` WHERE `open_id`='".$openId."'";
        $q = $this->db->query($sql);
        if ($q->row['customer_in_shop_id']){
            return $q->row['customer_in_shop_id'];
        }else{
            $sql = "INSERT INTO `".DB_PREFIX."customer_in_shop` SET `open_id`='".$openId."',`shop_id`='".$shopid."'";
            $this->db->query($sql);
            return $this->db->getLastId();
        }
    }

    /*
     * 同 ModelAccountCustomer->userCheckByTelephone()
     */
    public function _getUserIdByTel($tel) {
        $ret = array(
            'userId' => 0,//user表pk，记录操作人信息
            'saleId' => 0,//业务员pk，业务员角色获取订单、客户、数据报表
            'logcenterId' => 0,//物流中心pk，仓管角色获取订单、出库单
        );
        $sql = "SELECT * FROM `".DB_PREFIX."user` WHERE `contact_tel`='".$tel."'";
        $q = $this->db->query($sql);
        if ($q->num_rows){
            $tmp = $q->row;
            $ret['userId'] = $tmp['user_id'];
            $ret['logcenterId'] = $tmp['logcenter_permission'];
            // if (63 == $tmp['user_group_id']) {
            //     $ret['saleId'] = $tmp['user_id'];
            // }
        }
        return $ret;
    }

    public function telCheck($tel) {
        $sql = "SELECT `customer_id` FROM `".DB_PREFIX.$this->_defaultDB."` WHERE `telephone`='".$this->db->escape($tel)."'";
        $q = $this->db->query($sql);
        return $q->row['customer_id'];
    }

    public function saveSmsMobile($tel, $code) {
        $sql = "SELECT `sms_mobile_id` FROM `".DB_PREFIX."sms_mobile` WHERE `sms_mobile`='".$this->db->escape($tel)."'";
        $q = $this->db->query($sql);
        if ($q->row['sms_mobile_id']) {
            $sql = "UPDATE `".DB_PREFIX."sms_mobile` SET `sms_mobile`='".$this->db->escape($tel)."',`verify_code`='".$code."',`create_time`='".date('Y-m-d H:i:s')."' WHERE `sms_mobile_id`='".$q->row['sms_mobile_id']."'";
        }else{
            $sql = "INSERT INTO `".DB_PREFIX."sms_mobile` SET `sms_mobile`='".$tel."',`verify_code`='".$code."',`create_time`='".date('Y-m-d H:i:s')."'";
        }
        $this->db->query($sql);
    }

    public function smsCodeCheck($tel, $code) {
        $sql = "SELECT `sms_mobile_id`,`create_time` FROM `".DB_PREFIX."sms_mobile` WHERE `sms_mobile`='".$this->db->escape($tel)."' AND `verify_code`='".$this->db->escape($code)."'";
        $q = $this->db->query($sql);
        if ($q->row['sms_mobile_id']) {
            $dateAdded = strtotime($q->row['create_time']);
            $now = time();
            if (($now-$dateAdded) < 3600) {//验证码有效期60分钟
                $sql = "DELETE FROM `".DB_PREFIX."sms_mobile` WHERE `sms_mobile_id`='".$q->row['sms_mobile_id']."'";
                $this->db->query($sql);
                return true;
            }else{
                return false;
            }
        }else{
            return false;
        }
    }

    public function addNew($info) {
        if (count($info)) {
            $temp = array();
            foreach ($info as $col=>$val) {
                $temp[] = "`".$col."`='".$this->db->escape($val)."'";
            }
            $sql = "INSERT INTO `".DB_PREFIX.$this->_defaultDB."` SET ".implode(',', $temp);
            $this->db->query($sql);
            return $this->db->getLastId();
        }
    }

    public function getOpenIdByCustomerInShopId($pk) {
        $sql = "SELECT `open_id` FROM `".DB_PREFIX."customer_in_shop` WHERE `customer_in_shop_id`='".$pk."'";
        $q = $this->db->query($sql);
        return $q->row['open_id'];
    }

    public function addCustomerImages($info) {
        if (count($info)) {
            $temp = array();
            foreach ($info as $col=>$val) {
                $temp[] = "`".$col."`='".$this->db->escape($val)."'";
            }
            $sql = "INSERT INTO `".DB_PREFIX."customer_images` SET ".implode(',', $temp);
            $this->db->query($sql);
            return $this->db->getLastId();
        }
    }

    public function modifyByPK($pk, $info) {
        if ($pk && count($info)) {
            $temp = array();
            foreach ($info as $col=>$val) {
                $temp[] = "`".$col."`='".$this->db->escape($val)."'";
            }
            $sql = "UPDATE `".DB_PREFIX.$this->_defaultDB."` SET ".implode(',', $temp)." WHERE `customer_id`='".$pk."'";
            echo $sql;
            $this->db->query($sql);
        }
    }

    public function addUpload($info) {
        if (count($info)) {
            $temp = array();
            foreach ($info as $col=>$val) {
                $temp[] = "`".$col."`='".$this->db->escape($val)."'";
            }
            $sql = "INSERT INTO `".DB_PREFIX."upload` SET ".implode(',', $temp);
            $this->db->query($sql);
            return $this->db->getLastId();
        }
    }

    public function updateUploadByPK($pk, $info) {
        if ($pk && count($info)) {
            $temp = array();
            foreach ($info as $col=>$val) {
                $temp[] = "`".$col."`='".$this->db->escape($val)."'";
            }
            $sql = "UPDATE `".DB_PREFIX."upload` SET ".implode(',', $temp)." WHERE `upload_id`='".$pk."'";
            $this->db->query($sql);
        }
    }
}
